<template>
	<div class="flex space-x-1">
		<ypselect
			:itemList="item"
			v-model="path[index]"
			v-for="(item, index) in group"
			:key="index"
			@click.capture="change(index)"
		></ypselect>
	</div>
</template>
<script setup>
	import { getData } from '@/common/base'
	import { ref, onMounted, reactive, watch } from 'vue'
	const props = defineProps({
		modelValue: {
			default: [],
		},
		pid: {
			default: 0,
		},
	})
	const emit = defineEmits(['update:modelValue'])
	//保存父级ID
	const pid = ref(props.pid)
	const path = reactive(props.modelValue || [])
	watch(
		() => props.modelValue,
		(newVal) => {
			for (const value of newVal) {
				path.length = 0
				pos.value = 0
				path.push(value)
			}
		}
	)
	const pos = ref(0)
	const group = reactive([])
	const noupdatePath = ref(false)
	//菜单更新
	watch(path, (newVal) => {
		if (noupdatePath.value) {
			return
		}
		pid.value = newVal[pos.value]
		if (newVal[pos.value]) {
			getList()
			emit('update:modelValue', newVal)
		} else {
			group.length = pos.value + 1
			noupdatePath.value = true
			path.length = pos.value + 1
		}
	})
	//获取数据
	const getList = async () => {
		if (typeof pid.value == 'undefined') {
			return
		}
		const res = await getData('classify/getSelect', {
			pid: pid.value,
			ids: path,
		})
		if (res.code == 1) {
			if (group.length) {
				group.length = pos.value + 1
				path.length = pos.value + 1
			}
			res.data.forEach((item) => {
				let options = []
				Object.keys(item).forEach((key) => {
					options.push({
						title: item[key].title,
						id: item[key].id,
					})
				})
				group.push(options)
			})
		}
	}

	const change = (index) => {
		noupdatePath.value = false
		pos.value = index
	}
	onMounted(() => {
		getList()
	})
</script>
